// 游戏配置
const CONFIG = {
    CANVAS_WIDTH: 800,
    CANVAS_HEIGHT: 600,
    GRID_SIZE: 40,
    TANK_SPEED: 2,
    BULLET_SPEED: 4,
    ENEMY_COUNT: 5,
    POWERUP_CHANCE: 0.3
};

// 游戏状态
let gameState = 'menu'; // menu, playing, paused, gameOver
let gameMode = 'single'; // single, multi
let level = 1;
let score = { player1: 0, player2: 0 };
let lives = { player1: 3, player2: 3 };

// 游戏对象
let player1 = null;
let player2 = null;
let enemies = [];
let bullets = [];
let blocks = [];
let powerUps = [];

// 画布和上下文
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');

// 输入处理
const keys = {};

// 游戏类定义
class Tank {
    constructor(x, y, color, controls) {
        this.x = x;
        this.y = y;
        this.width = 35;
        this.height = 35;
        this.color = color;
        this.direction = 0; // 0: 上, 1: 右, 2: 下, 3: 左
        this.speed = CONFIG.TANK_SPEED;
        this.controls = controls;
        this.lastShot = 0;
        this.shootCooldown = 500; // 毫秒
    }

    update() {
        if (!this.controls) return;

        // 移动逻辑
        let newX = this.x;
        let newY = this.y;

        if (keys[this.controls.up]) {
            this.direction = 0;
            newY -= this.speed;
        }
        if (keys[this.controls.down]) {
            this.direction = 2;
            newY += this.speed;
        }
        if (keys[this.controls.left]) {
            this.direction = 3;
            newX -= this.speed;
        }
        if (keys[this.controls.right]) {
            this.direction = 1;
            newX += this.speed;
        }

        // 边界检查
        if (newX >= 0 && newX <= CONFIG.CANVAS_WIDTH - this.width) {
            this.x = newX;
        }
        if (newY >= 0 && newY <= CONFIG.CANVAS_HEIGHT - this.height) {
            this.y = newY;
        }

        // 射击逻辑
        if (keys[this.controls.shoot] && Date.now() - this.lastShot > this.shootCooldown) {
            this.shoot();
            this.lastShot = Date.now();
        }
    }

    shoot() {
        let bulletX = this.x + this.width / 2;
        let bulletY = this.y + this.height / 2;

        switch (this.direction) {
            case 0: bulletY -= this.height / 2; break;
            case 1: bulletX += this.width / 2; break;
            case 2: bulletY += this.height / 2; break;
            case 3: bulletX -= this.width / 2; break;
        }

        bullets.push(new Bullet(bulletX, bulletY, this.direction, this.color));
    }

    draw() {
        ctx.save();
        ctx.translate(this.x + this.width / 2, this.y + this.height / 2);
        ctx.rotate(this.direction * Math.PI / 2);
        
        // 坦克主体
        ctx.fillStyle = this.color;
        ctx.fillRect(-this.width / 2, -this.height / 2, this.width, this.height);
        
        // 坦克炮管
        ctx.fillStyle = '#333';
        ctx.fillRect(-5, -this.height / 2 - 10, 10, 20);
        
        ctx.restore();
    }
}

class Enemy extends Tank {
    constructor(x, y) {
        super(x, y, '#e74c3c', null);
        this.direction = Math.floor(Math.random() * 4);
        this.changeDirectionCounter = 0;
        this.aiShootCounter = 0;
    }

    update() {
        // AI移动逻辑
        this.changeDirectionCounter++;
        this.aiShootCounter++;

        if (this.changeDirectionCounter > 60) {
            this.direction = Math.floor(Math.random() * 4);
            this.changeDirectionCounter = 0;
        }

        let newX = this.x;
        let newY = this.y;

        switch (this.direction) {
            case 0: newY -= this.speed; break;
            case 1: newX += this.speed; break;
            case 2: newY += this.speed; break;
            case 3: newX -= this.speed; break;
        }

        // 边界检查
        if (newX >= 0 && newX <= CONFIG.CANVAS_WIDTH - this.width) {
            this.x = newX;
        } else {
            this.direction = (this.direction + 2) % 4; // 反向
        }
        if (newY >= 0 && newY <= CONFIG.CANVAS_HEIGHT - this.height) {
            this.y = newY;
        } else {
            this.direction = (this.direction + 2) % 4; // 反向
        }

        // AI射击
        if (this.aiShootCounter > 90 && Math.random() < 0.02) {
            this.shoot();
            this.aiShootCounter = 0;
        }
    }
}

class Bullet {
    constructor(x, y, direction, color) {
        this.x = x;
        this.y = y;
        this.radius = 3;
        this.direction = direction;
        this.speed = CONFIG.BULLET_SPEED;
        this.color = color;
        this.active = true;
    }

    update() {
        switch (this.direction) {
            case 0: this.y -= this.speed; break;
            case 1: this.x += this.speed; break;
            case 2: this.y += this.speed; break;
            case 3: this.x -= this.speed; break;
        }

        // 边界检查
        if (this.x < 0 || this.x > CONFIG.CANVAS_WIDTH || 
            this.y < 0 || this.y > CONFIG.CANVAS_HEIGHT) {
            this.active = false;
        }
    }

    draw() {
        ctx.fillStyle = this.color;
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
        ctx.fill();
    }
}

class Block {
    constructor(x, y, type) {
        this.x = x;
        this.y = y;
        this.width = CONFIG.GRID_SIZE;
        this.height = CONFIG.GRID_SIZE;
        this.type = type; // 0: 可破坏, 1: 不可破坏
        this.health = type === 0 ? 2 : Infinity;
    }

    hit() {
        if (this.type === 0) {
            this.health--;
            return this.health <= 0;
        }
        return false;
    }

    draw() {
        if (this.type === 0) {
            ctx.fillStyle = '#8B4513'; // 砖墙
        } else {
            ctx.fillStyle = '#696969'; // 钢墙
        }
        ctx.fillRect(this.x, this.y, this.width, this.height);
        ctx.strokeStyle = '#333';
        ctx.strokeRect(this.x, this.y, this.width, this.height);
    }
}

class PowerUp {
    constructor(x, y, type) {
        this.x = x;
        this.y = y;
        this.width = 30;
        this.height = 30;
        this.type = type; // 0: 加速, 1: 加血, 2: 火力
        this.active = true;
    }

    draw() {
        ctx.fillStyle = '#FFD700';
        ctx.fillRect(this.x, this.y, this.width, this.height);
        ctx.strokeStyle = '#FFA500';
        ctx.strokeRect(this.x, this.y, this.width, this.height);
        
        // 绘制图标
        ctx.fillStyle = '#000';
        ctx.font = '20px Arial';
        const symbols = ['⚡', '❤️', '🔥'];
        ctx.fillText(symbols[this.type], this.x + 5, this.y + 22);
    }
}

// 游戏初始化
function initGame() {
    // 重置游戏状态
    enemies = [];
    bullets = [];
    blocks = [];
    powerUps = [];
    
    // 创建玩家
    player1 = new Tank(100, 500, '#3498db', {
        up: 'KeyW',
        down: 'KeyS',
        left: 'KeyA',
        right: 'KeyD',
        shoot: 'Space'
    });

    if (gameMode === 'multi') {
        player2 = new Tank(700, 500, '#2ecc71', {
            up: 'ArrowUp',
            down: 'ArrowDown',
            left: 'ArrowLeft',
            right: 'ArrowRight',
            shoot: 'Enter'
        });
    } else {
        player2 = null;
    }

    // 创建敌人
    for (let i = 0; i < CONFIG.ENEMY_COUNT; i++) {
        const x = Math.random() * (CONFIG.CANVAS_WIDTH - 40);
        const y = Math.random() * 200;
        enemies.push(new Enemy(x, y));
    }

    // 创建地图
    generateMap();
}

function generateMap() {
    const gridWidth = Math.floor(CONFIG.CANVAS_WIDTH / CONFIG.GRID_SIZE);
    const gridHeight = Math.floor(CONFIG.CANVAS_HEIGHT / CONFIG.GRID_SIZE);

    for (let y = 0; y < gridHeight; y++) {
        for (let x = 0; x < gridWidth; x++) {
            if (Math.random() < 0.2 && !(x < 3 && y > 10) && !(x > 17 && y > 10)) {
                const type = Math.random() < 0.7 ? 0 : 1;
                blocks.push(new Block(x * CONFIG.GRID_SIZE, y * CONFIG.GRID_SIZE, type));
            }
        }
    }
}

// 碰撞检测
function checkCollisions() {
    // 子弹与方块
    bullets.forEach(bullet => {
        blocks.forEach((block, blockIndex) => {
            if (bullet.x > block.x && bullet.x < block.x + block.width &&
                bullet.y > block.y && bullet.y < block.y + block.height) {
                bullet.active = false;
                if (block.hit()) {
                    blocks.splice(blockIndex, 1);
                    
                    // 随机掉落道具
                    if (Math.random() < CONFIG.POWERUP_CHANCE) {
                        const type = Math.floor(Math.random() * 3);
                        powerUps.push(new PowerUp(block.x + 5, block.y + 5, type));
                    }
                }
            }
        });
    });

    // 子弹与坦克
    bullets.forEach((bullet, bulletIndex) => {
        // 检查与玩家1的碰撞
        if (player1 && bullet.color !== player1.color &&
            bullet.x > player1.x && bullet.x < player1.x + player1.width &&
            bullet.y > player1.y && bullet.y < player1.y + player1.height) {
            bullet.active = false;
            lives.player1--;
            if (lives.player1 <= 0) {
                gameOver();
            }
        }

        // 检查与玩家2的碰撞
        if (player2 && bullet.color !== player2.color &&
            bullet.x > player2.x && bullet.x < player2.x + player2.width &&
            bullet.y > player2.y && bullet.y < player2.y + player2.height) {
            bullet.active = false;
            lives.player2--;
            if (lives.player2 <= 0) {
                gameOver();
            }
        }

        // 检查与敌人的碰撞
        enemies.forEach((enemy, enemyIndex) => {
            if (bullet.color !== enemy.color &&
                bullet.x > enemy.x && bullet.x < enemy.x + enemy.width &&
                bullet.y > enemy.y && bullet.y < enemy.y + enemy.height) {
                bullet.active = false;
                enemies.splice(enemyIndex, 1);
                
                if (bullet.color === player1.color) {
                    score.player1 += 100;
                } else if (player2 && bullet.color === player2.color) {
                    score.player2 += 100;
                }
            }
        });
    });

    // 玩家与道具
    powerUps.forEach((powerUp, index) => {
        const checkPlayer = (player) => {
            if (player && powerUp.active &&
                player.x < powerUp.x + powerUp.width &&
                player.x + player.width > powerUp.x &&
                player.y < powerUp.y + powerUp.height &&
                player.y + player.height > powerUp.y) {
                powerUp.active = false;
                powerUps.splice(index, 1);
                applyPowerUp(player, powerUp.type);
            }
        };
        
        checkPlayer(player1);
        if (gameMode === 'multi') {
            checkPlayer(player2);
        }
    });
}

function applyPowerUp(player, type) {
    switch (type) {
        case 0: // 加速
            player.speed = Math.min(player.speed + 1, 5);
            break;
        case 1: // 加血
            if (player === player1) {
                lives.player1 = Math.min(lives.player1 + 1, 5);
            } else if (player === player2) {
                lives.player2 = Math.min(lives.player2 + 1, 5);
            }
            break;
        case 2: // 火力
            player.shootCooldown = Math.max(player.shootCooldown - 100, 200);
            break;
    }
}

// 游戏循环
function gameLoop() {
    if (gameState !== 'playing') return;

    // 清空画布
    ctx.clearRect(0, 0, CONFIG.CANVAS_WIDTH, CONFIG.CANVAS_HEIGHT);

    // 更新和绘制方块
    blocks.forEach(block => block.draw());

    // 更新和绘制道具
    powerUps.forEach(powerUp => {
        if (powerUp.active) powerUp.draw();
    });

    // 更新和绘制玩家
    if (player1) {
        player1.update();
        player1.draw();
    }
    if (player2) {
        player2.update();
        player2.draw();
    }

    // 更新和绘制敌人
    enemies.forEach(enemy => {
        enemy.update();
        enemy.draw();
    });

    // 更新和绘制子弹
    bullets.forEach(bullet => {
        bullet.update();
        if (bullet.active) {
            bullet.draw();
        }
    });

    // 清理不活跃的子弹
    bullets = bullets.filter(bullet => bullet.active);

    // 检查胜利条件
    if (enemies.length === 0) {
        level++;
        initGame();
    }

    // 碰撞检测
    checkCollisions();

    // 更新UI
    updateUI();

    requestAnimationFrame(gameLoop);
}

function updateUI() {
    document.getElementById('score1').textContent = score.player1;
    document.getElementById('lives1').textContent = lives.player1;
    
    if (gameMode === 'multi') {
        document.getElementById('score2Container').style.display = 'inline';
        document.getElementById('score2').textContent = score.player2;
        document.getElementById('lives2').textContent = lives.player2;
    } else {
        document.getElementById('score2Container').style.display = 'none';
    }
}

function gameOver() {
    gameState = 'gameOver';
    const totalScore = score.player1 + (gameMode === 'multi' ? score.player2 : 0);
    document.getElementById('finalScore').textContent = `最终得分: ${totalScore}`;
    document.getElementById('gameOver').style.display = 'block';
}

// 事件监听
document.addEventListener('keydown', (e) => {
    keys[e.code] = true;
    e.preventDefault();
});

document.addEventListener('keyup', (e) => {
    keys[e.code] = false;
    e.preventDefault();
});

// 菜单事件
document.getElementById('singlePlayerBtn').addEventListener('click', () => {
    gameMode = 'single';
    gameState = 'playing';
    document.getElementById('gameMenu').style.display = 'none';
    initGame();
    gameLoop();
});

document.getElementById('multiPlayerBtn').addEventListener('click', () => {
    gameMode = 'multi';
    gameState = 'playing';
    document.getElementById('gameMenu').style.display = 'none';
    initGame();
    gameLoop();
});

document.getElementById('helpBtn').addEventListener('click', () => {
    document.getElementById('gameMenu').style.display = 'none';
    document.getElementById('helpMenu').style.display = 'block';
});

document.getElementById('backBtn').addEventListener('click', () => {
    document.getElementById('helpMenu').style.display = 'none';
    document.getElementById('gameMenu').style.display = 'block';
});

document.getElementById('restartBtn').addEventListener('click', () => {
    score = { player1: 0, player2: 0 };
    lives = { player1: 3, player2: 3 };
    level = 1;
    document.getElementById('gameOver').style.display = 'none';
    gameState = 'playing';
    initGame();
    gameLoop();
});

document.getElementById('menuBtn').addEventListener('click', () => {
    score = { player1: 0, player2: 0 };
    lives = { player1: 3, player2: 3 };
    level = 1;
    document.getElementById('gameOver').style.display = 'none';
    document.getElementById('gameMenu').style.display = 'block';
    gameState = 'menu';
});
